package com.jinkaimen.kqb.ui.activity.addmerchant;

import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.ht.baselibs.core.EventCenter;
import com.ht.baselibs.core.EventCode;
import com.ht.baselibs.retrofit.NetCallBack;
import com.ht.baselibs.ui.base.BaseActivity;
import com.ht.baselibs.ui.widget.TitleBarView;
import com.ht.baselibs.utils.ActivityUtils;
import com.ht.baselibs.utils.SharedPreferencesUtils;
import com.ht.baselibs.utils.UIUtils;
import com.jinkaimen.kqb.R;
import com.jinkaimen.kqb.bean.AppbizCard;
import com.jinkaimen.kqb.bean.BankCardBean;
import com.jinkaimen.kqb.bean.SearchShopBean;
import com.jinkaimen.kqb.dao.AccountDao;
import com.jinkaimen.kqb.manager.ApiManager;
import com.jinkaimen.kqb.ui.weiget.CardInputEditText;
import com.jinkaimen.kqb.utils.IDCardUtil;

import de.greenrobot.event.EventBus;
import retrofit2.Call;
import retrofit2.Response;

public class IdentificationShopStep4Activity extends BaseActivity {

    private TextView mBankNameView;
    private CardInputEditText mCardNoView;
    private TextView mBranchNameView;
    private EditText mNameView;
    private EditText mIdCardView;
    private boolean mIsPublic;
    private RelativeLayout rl_area;
    private TextView et_atea;
    private RelativeLayout rl_place_bank;
    private String branchDistrictCode;
    private String mSelectCityName;
    private String cardBank = "";
    private ImageView iv_can_puss;
    private String branchCode;
    private long mShopId;
    private long mUserId;
    private boolean canEdit = true;
    private TextView mNextButton;
    private RelativeLayout rl_open_function;
    private TextView et_open_function;
    private boolean isOpenWeixin;
    private boolean isOpenZhifubao;
    private boolean isOpenD0;
    public static final int REQUEST_CODE_OPEN_SERVICE = 800;
    private String wechatTradeRateT1;
    private String alipayTradeRateT1;


    @Override
    protected boolean isStaticPage() {
        return true;
    }

    @Override
    protected void initTitleBar() {


        if (canEdit) {
            mTitleBarView
                    .setLeftBtnIcon(View.GONE)
                    .setTitleText("填写结算账户").addActions(
                    new TitleBarView.Action("上一步") {
                        @Override
                        public void performAction(View view) {
                            Bundle bundle = new Bundle();
                            bundle.putLong("report_shop_id", mShopId);
                            bundle.putBoolean("canEdit", true);
                            bundle.putLong("report_account_id", mUserId);
                            ActivityUtils.startActivityAndFinish(IdentificationShopStep4Activity.this, IdentificationShopStep2Activity.class, bundle);
                        }
                    }
            );//
//                    .setTitleTextColor(R.color.black)
//                    .setBackgroundColor(getResources().getColor(R.color.white));
        } else {
            mTitleBarView.setTitleText("填写结算账户").addActions(
                    new TitleBarView.Action("下一步") {
                        @Override
                        public void performAction(View view) {
                            ActivityUtils.finishActivity(IdentificationShopStep4Activity.this);
                        }
                    }
            );
        }
    }

    @Override
    protected int initContentView() {
        return R.layout.activity_identification_shop_step4_add_merchant;
    }

    @Override
    protected void initIntentData(Intent callIntent) {
//        mIsPublic = callIntent.getBooleanExtra("isPublic", false);
        mShopId = callIntent.getLongExtra("report_shop_id", 0);
        mUserId = callIntent.getLongExtra("report_account_id", 0);
        canEdit = callIntent.getBooleanExtra("canEdit", true);
//        String isPublicTemp = (String) AppApplication.getTempData("isPublic");
//        mIsPublic = "0".equals(isPublicTemp) ? false : true;
    }

    @Override
    protected void initChildView() {
        rl_area = (RelativeLayout) findViewById(R.id.rl_area);
        et_atea = (TextView) findViewById(R.id.et_atea);
        rl_place_bank = (RelativeLayout) findViewById(R.id.rl_place_bank);
        iv_can_puss = (ImageView) findViewById(R.id.iv_can_puss);

        Drawable drawable = getResources().getDrawable(R.mipmap.identification_step1_end);
        drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());

        mNameView = (EditText) findViewById(R.id.et_activity_identification_shop_step4_name);
        mIdCardView = (EditText) findViewById(R.id.et_activity_identification_shop_step4_idcard);
        mCardNoView = (CardInputEditText) findViewById(R.id.et_activity_identification_shop_step4_card_no);
        mBankNameView = (TextView) findViewById(R.id.et_activity_identification_shop_step4_bank_name);
        mNextButton = (TextView) findViewById(R.id.btn_activity_identification_shop);
        mBranchNameView = (TextView) findViewById(R.id.et_activity_identification_shop_step4_branch_name);
        rl_open_function = (RelativeLayout) findViewById(R.id.rl_open_function);
        et_open_function = (TextView) findViewById(R.id.et_open_function);

        if (mIsPublic) {
            mIdCardView.setHint("法人二代身份证");
            mCardNoView.setHint("输入对公账户银行卡号");


        } else {
            mIdCardView.setHint("请输入二代身份证号");
            mCardNoView.setHint("输入本人名下借记银行卡号");
        }
        if (canEdit) {
            mNameView.setEnabled(true);
            mIdCardView.setEnabled(true);
            mCardNoView.setEnabled(true);
            rl_open_function.setClickable(true);
            rl_open_function.setEnabled(true);
            mNextButton.setVisibility(View.VISIBLE);
        } else {
            mNameView.setEnabled(false);
            mIdCardView.setEnabled(false);
            mCardNoView.setEnabled(false);
            rl_open_function.setClickable(false);
            rl_open_function.setEnabled(false);
            mNextButton.setVisibility(View.GONE);
        }
    }

    @Override
    protected void initChildData() {

        showLoadingDialog();
        ApiManager.getApi().searchShopInfo(
                "INV_HSY001010",
                mUserId
        ).enqueue(new NetCallBack<SearchShopBean>() {
            @Override
            protected void onSuccess(Call<SearchShopBean> call, Response<SearchShopBean> response) {
                AppbizCard bizShopBean = new AppbizCard();
                try {
                    bizShopBean = response.body().appbizCard;
                } catch (Exception e) {
                    e.printStackTrace();
                }

                String cardNO = bizShopBean.cardNO;
                cardBank = bizShopBean.cardBank;
                String cardAccountName = bizShopBean.cardAccountName;
                String bankAddress = bizShopBean.bankAddress;
                String idcard = bizShopBean.idcardNO;
                branchCode = bizShopBean.branchCode;
                branchDistrictCode = bizShopBean.branchDistrictCode;
                String branchDistrictName = bizShopBean.branchDistrictName;
                mIsPublic = response.body().appBizShop.isPublic == 1 ? true : false;
                if (mIsPublic) {
                    mIdCardView.setHint("法人二代身份证");
                    mCardNoView.setHint("输入对公账户银行卡号");
                    mBankNameView.setHint("请选择开户银行");
                } else {
                    mIdCardView.setHint("请输入二代身份证号");
                    mCardNoView.setHint("输入本人名下借记银行卡号");
                    mBankNameView.setHint("自动匹配开户银行");
                }
                try {
                    String[] split = branchDistrictName.split("\\|");
                    if (split.length == 3) {
                        branchDistrictName = split[1] + "/" + split[2];
                    } else if (split.length == 2) {
                        branchDistrictName = split[0] + "/" + split[1];
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
//                if (mIsPublic) {
//                    mIdCardView.setHint("法人二代身份证");
//                    mCardNoView.setHint("输入对公账户银行卡号");
//                } else {
//                    mIdCardView.setHint("请输入二代身份证号");
//                    mCardNoView.setHint("输入对公账户银行卡号");
//                }
                mCardNoView.setText(cardNO);
                mBankNameView.setText(cardBank);
                mNameView.setText(cardAccountName);
                mBranchNameView.setText(bankAddress);
                mIdCardView.setText(idcard);
                et_atea.setText(branchDistrictName);

            }

            @Override
            protected boolean isNullNeedCallback() {
                return true;
            }

            @Override
            protected void hiddenProgress() {
                hideLodingDialog();
            }
        });
    }


    @Override
    protected void setChildViewListener() {
        mNextButton.setOnClickListener(this);
        mBankNameView.setOnClickListener(this);
        mCardNoView.setOnClickListener(this);
        rl_area.setOnClickListener(this);
        rl_place_bank.setOnClickListener(this);
        rl_open_function.setOnClickListener(this);
        if (mIsPublic) {
            return;
        }
        mCardNoView.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {

                if (!hasFocus && !mIsPublic) {
                    String cardNO = mCardNoView.getTextWithoutSpace();
                    if (TextUtils.isEmpty(cardNO)) {
                        UIUtils.showToast("请输入结算卡号");
                        return;
                    }


                    if (cardNO.length() < 6 || cardNO.length() > 19) {
                        UIUtils.showToast("请输入正确的结算卡号");
                        return;
                    }


                    showLoadingDialog();
                    ApiManager.getApi().getBankCardInfo(
                            "INV_HSY001006",
                            cardNO
                    ).enqueue(new NetCallBack<BankCardBean>() {
                        @Override
                        protected void onSuccess(Call<BankCardBean> call, Response<BankCardBean> response) {
                            EventBus.getDefault().post(new EventCenter(EventCode.EVENT_CODE_AUTHOR_SUCCESS));
                            BankCardBean mBankCardBean = new BankCardBean();
                            if (response != null) {
                                mBankCardBean = response.body();
                            }
                            cardBank = mBankCardBean.bankName;
                            if (TextUtils.isEmpty(cardBank)) {
                                UIUtils.showToast("您输入的卡号有误或为暂不支持该银行卡");
                            } else {
                                mBankNameView.setText(cardBank);
                            }
                            mBankNameView.setText(mBankCardBean.bankName);

                        }

                        @Override
                        protected void hiddenProgress() {
                            hideLodingDialog();
                        }

                        @Override
                        public void onFailure(Call<BankCardBean> call, Throwable t) {
//                            super.onFailure(call, t);
                            UIUtils.showToast("您输入的卡号有误请重新输入");
                        }
                    });
                }
            }
        });
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()) {
            case R.id.btn_activity_identification_shop:

                if (mIsPublic) {
                    String name2 = mBankNameView.getText().toString().trim();
                    if (TextUtils.isEmpty(name2)) {
                        UIUtils.showToast("请输入开户行");
                    }
                }
                String idcardNO = mIdCardView.getText().toString();
                if (TextUtils.isEmpty(idcardNO)) {
                    UIUtils.showToast("请输入身份证号");
                    return;
                }

                IDCardUtil.Result result = IDCardUtil.validateIDNum(idcardNO.toUpperCase());

                if (!result.isMatch()) {
                    UIUtils.showToast("身份证号格式不正确,请重新输入");
                    return;
                }
                String cardNo = mCardNoView.getTextWithoutSpace();
                if (TextUtils.isEmpty(cardNo)) {
                    UIUtils.showToast("请输入卡号");
                    return;
                }
                String name2 = mBankNameView.getText().toString().trim();
                if (TextUtils.isEmpty(name2)) {
                    UIUtils.showToast("请输入正确的卡号或联系客服");
                }

                String bankAddress = mBranchNameView.getText().toString();
                if (TextUtils.isEmpty(bankAddress)) {
                    UIUtils.showToast("请输入开卡支行");
                    return;
                }

                String cardAccountName = mNameView.getText().toString();
                if (TextUtils.isEmpty(cardAccountName)) {
                    UIUtils.showToast("请输入开户名");
                    return;
                }

                if (cardAccountName.length() > 25) {
                    UIUtils.showToast("开户名最大为25个字,请重新输入");
                    return;
                }


//                String idcardNO = mIdCardView.getText().toString();
                if (!SharedPreferencesUtils.getBool(IdentificationShopStep1Activity.IDENTIFICATION_SETTLEMENT_TYPE_IS_PUBLIC, false)) {
                    if (TextUtils.isEmpty(idcardNO)) {
                        UIUtils.showToast("请输入身份证卡号");
                        return;
                    }
                }



                String trim = et_open_function.getText().toString().trim();
                if (TextUtils.isEmpty(trim)) {
                    UIUtils.showToast("请设置费率");
                    return;
                }

                showLoadingDialog();
                ApiManager.getApi().sendCollectCard(
                        "INV_HSY001005",
                        cardNo,
                        cardBank,
                        cardAccountName,
                        mShopId,
                        bankAddress,
                        idcardNO,
                        branchCode,
                        branchDistrictCode

                ).enqueue(new NetCallBack<String>() {
                    @Override
                    protected void onSuccess(Call<String> call, Response<String> response) {
                        AccountDao.getInstance().authorStep(4);
                        EventBus.getDefault().post(new EventCenter(EventCode.EVENT_CODE_AUTHOR_SUCCESS));
                        Bundle bundle = new Bundle();
                        bundle.putLong("report_account_id", mUserId);
                        bundle.putLong("report_shop_id", mShopId);
                        ActivityUtils.startActivityAndFinish(IdentificationShopStep4Activity.this, BindQrCodeActivity.class, bundle);
                    }

                    @Override
                    protected boolean isNullNeedCallback() {
                        return true;
                    }

                    @Override
                    protected void hiddenProgress() {
                        hideLodingDialog();
                    }
                });

                break;
            case R.id.rl_area:
                if (!canEdit) {
                    return;
                }
                rl_area.setFocusable(true);
                rl_area.setFocusableInTouchMode(true);
                rl_area.requestFocus();
                Bundle bundle = new Bundle();
                bundle.putString(SelectLocationActivity.BANK_LOCATION, mSelectCityName);
                ActivityUtils.startActivityForResult(this, SelectLocationActivity.class, bundle, SelectLocationActivity.REQUEST_CODE_SELECT_LOCATION_CITY);
                break;
            case R.id.rl_place_bank:
                if (!canEdit) {
                    return;
                }
                rl_place_bank.setFocusable(true);
                rl_place_bank.setFocusableInTouchMode(true);
                rl_place_bank.requestFocus();
                if (TextUtils.isEmpty(mBankNameView.getText().toString().trim())) {
                    UIUtils.showToast("请正确输入开户行卡号");
                    return;
                }
                if (TextUtils.isEmpty(et_atea.getText().toString().trim())) {
                    UIUtils.showToast("请选择所在地区");
                    return;
                }
                Bundle bundle1 = new Bundle();
                bundle1.putString("bankName", mBankNameView.getText().toString().trim());
                bundle1.putString("mSelectCityCode", branchDistrictCode);
                ActivityUtils.startActivityForResult(this, SearchBankActivity.class, bundle1, SearchBankActivity.REQUEST_CODE_BANK_NAME);
                break;
            case R.id.et_activity_identification_shop_step4_bank_name:
                if (!canEdit) {
                    return;
                }
                if (mIsPublic) {
                    ActivityUtils.startActivityForResult(this, SearchFatherBankActivity.class, SearchFatherBankActivity.REQUEST_CODE_FATHER_BANK_NAME);
                } else {
                    mCardNoView.setFocusable(false);
                    mCardNoView.setFocusable(true);
                    mCardNoView.setFocusableInTouchMode(false);
                }
                break;
            case R.id.et_activity_identification_shop_step4_card_no:
                if (!canEdit) {
                    return;
                }
                mCardNoView.setFocusable(true);
                mCardNoView.setFocusableInTouchMode(true);
                mCardNoView.requestFocus();
                break;
            case R.id.rl_open_function:
// TODO: 2017/6/8
                Bundle bundle2 = new Bundle();
                bundle2.putBoolean("isOpenWeixin", isOpenWeixin);
                bundle2.putBoolean("isOpenZhifubao", isOpenZhifubao);
                bundle2.putLong("report_shop_id", mShopId);
                bundle2.putLong("report_account_id", mUserId);
                ActivityUtils.startActivityForResult(IdentificationShopStep4Activity.this, OpenServiceActivity.class, bundle2, REQUEST_CODE_OPEN_SERVICE);
                break;

        }

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case SelectLocationActivity.REQUEST_CODE_SELECT_LOCATION_CITY:
                    branchDistrictCode = data.getStringExtra("cityCode");
                    if (branchDistrictCode != null) {
                        mSelectCityName = data.getStringExtra("cityName") + "/" + data.getStringExtra("areaName");
                        et_atea.setText(mSelectCityName);
                    }
                    break;
                case SearchBankActivity.REQUEST_CODE_BANK_NAME:
                    String bankName = data.getStringExtra("bankName");
                    branchCode = data.getStringExtra("branchCode");
                    mBranchNameView.setText(bankName);
                    break;
                case SearchFatherBankActivity.REQUEST_CODE_FATHER_BANK_NAME:
                    String fatherBankName = data.getStringExtra("bankName");
                    cardBank = fatherBankName;
                    mBankNameView.setText(fatherBankName);
                    break;
                case REQUEST_CODE_OPEN_SERVICE:
                    Boolean isOpenWeixin = data.getBooleanExtra("isOpenWeixin", false);
                    Boolean isOpenZhifubao = data.getBooleanExtra("isOpenZhifubao", false);
                    Boolean isOpenD0 = data.getBooleanExtra("isOpenD0", false);
                    wechatTradeRateT1 = data.getStringExtra("wechatTradeRateT1");
                    alipayTradeRateT1 = data.getStringExtra("alipayTradeRateT1");
                    String name1 = isOpenWeixin ? "微信" : "";
                    String name2 = isOpenZhifubao ? (isOpenWeixin ? "、支付宝" : "支付宝") : "";
                    String name3 = isOpenD0 ? ((isOpenWeixin || isOpenZhifubao) ? "、D0" : "D0") : "";
                    et_open_function.setText(name1 + name2 + name3);
                    break;
            }
        }
    }

    @Override
    protected boolean hasEvent() {
        return true;
    }

    @Override
    protected void onEvent(int eventCode, Object data) {
        super.onEvent(eventCode, data);
        switch (eventCode) {
            case EventCode.EVENT_CODE_BANKNAME:
                Intent intent = (Intent) data;
                String brankname = intent.getStringExtra("bankName");
                branchCode = "-1";
                mBranchNameView.setText(brankname);
                break;

        }
    }


}
